package org.mogu.service;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.mogu.db.ActiveUserHelper;
import org.mogu.db.DBhelper;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.UrlSync;
import org.mogu.tools.UserUtil;

import org.mogu.R;
import org.mogu.TMain;
import org.mogu.Welcome;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.os.Binder;

import android.os.Handler;

public class InfoService extends Service {

	private Handler mMainHandler;

	InfoSync infoSync = new InfoSync();
//	ImgLibSync imgLibSync = new ImgLibSync();
	ImgSync imgSync = new ImgSync();
	GetSyncUrl getSyncUrl;
	DefaultHttpClient client;
	HttpResponse httpResponse;
	ActiveUserHelper auh;
	SQLiteDatabase readdb;
	SQLiteDatabase writedb;

	String uname;
	String pwd;
	String updateTime;

	Context context;

	ContentValues value;
	Intent i;
	
	 int numt=1;
	 
	int num = 0;
	/**
	 * 　　* 创建Handler对象，作为进程传递postDelayed之用
	 * 
	 * 　　
	 */

	private static final String TAG = "TService";

	private NotificationManager notificationManager;

	public void onCreate() {
		UserUtil.getUser(this);
		Convert.flag+=1;
		Log.d(TAG, "============> TService.onCreate");
		context = this;
		auh = DBhelper.getDBHelper(this);
		getSyncUrl=new GetSyncUrl(auh);
		getSyncUrl.init();

		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


		super.onCreate();
		mMainHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				// // 接收子线程的消息
				UrlSync urlSync=(UrlSync)msg.obj;
				if(msg.arg1==1){
					if(urlSync.isNotice()){
						putNotic(urlSync.getNoticeTitle(),urlSync.getNoticeContent(),urlSync.getNoticeCode());
					}else{
						if(urlSync.isToast()){
							if(urlSync.getToastContentSu()!=null){
								
							Toast.makeText(context, urlSync.getToastContentSu(), 4000).show();
							}
						}else{
							if(urlSync.getToastContentFa()!=null){
								
								Toast.makeText(context, urlSync.getToastContentFa(), 4000).show();
								}
						}
					}
				}else{
					Toast.makeText(context, "网络不给力。", 4000).show();
				}
				
			}

		};
	}

	private Handler handler = new Handler();
	private Handler imghandler = new Handler();

	public void onStart(Intent intent, int startId) {

		Log.i(TAG, "============> TService.onStart");
		super.onStart(intent, startId);
//		Toast.makeText(context, "~~~~~~"+Convert.flag, 4000).show();
		new Thread() {
			public void run() {
				Log.e("Service", "sync1");
				auh = DBhelper.getDBHelper(context);
				
				infoSync.sync(auh);
				getSyncUrl.getNeedSyncUrl();
				// auh.close();
				Log.e("Service", "sync4");
				long l=1000*60*10;
				Long long1;
				for (String key : Convert.userAppTimeSpanMap.keySet()) {
					long1=Convert.userAppTimeSpanMap.get(key);
					if(long1.longValue()<l){
						l=long1.longValue();
					}
				}
				
				handler.postDelayed(this, l);
				Log.e("Service", "sync5");
			}
		}.start();
		new Thread() {
			public void run() {

				// auh=DBhelper.getDBHelper(context);
				// sync(auh);//要定时执行的任务
				// auh.close();
				Log.e("Service", "sync6");
				imgsync();
				Log.e("Service", "sync7");

				imghandler.postDelayed(this, 1000 * 30 * 6);
				Log.e("Service", "sync8");
			}
		}.start();
		// imgsync();
		th.start();
	}

	public IBinder onBind(Intent intent) {

		Log.i(TAG, "============> TService.onBind");

		return null;
	}

	public class LocalBinder extends Binder {

		public InfoService getService() {

			return InfoService.this;
		}

	}

	public boolean onUnbind(Intent intent) {

		Log.i(TAG, "============> TService.onUnbind");

		return false;
	}

	public void onRebind(Intent intent) {

		Log.i(TAG, "============> TService.onRebind");
	}

	public void onDestroy() {

		Log.i(TAG, "============> TService.onDestroy");

		notificationManager.cancel(R.string.service_start);

		super.onDestroy();
	}

	public void showNotification(String title,String content) {
		i = new Intent(InfoService.this, TMain.class);
		 NotificationManager nm = (NotificationManager)
		 getSystemService(NOTIFICATION_SERVICE);
		 Notification n = new Notification(R.drawable.moguico, "蘑菇咨询",
		 System.currentTimeMillis());
		 n.flags = Notification.FLAG_AUTO_CANCEL;
		 // Intent i = new Intent(arg0.getContext(), NotificationShow.class);
		 //
		 i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
		 // PendingIntent
		 PendingIntent contentIntent = PendingIntent.getActivity(this,
		 R.string.app_name, i, PendingIntent.FLAG_UPDATE_CURRENT);
		
		 n.setLatestEventInfo(this, title, content, contentIntent);
		 nm.notify(numt++, n);
	}

	public void onDestory() {

	}

	public Thread th = new Thread() {
		public void run() {
//			Looper.prepare();
			UrlSync urlSync;
			
			while (true) {
				while (Convert.syncList.size() != 0) {
					urlSync = Convert.syncList.remove(0);
					request(urlSync);
					try {

						if (Convert.urlfail) {
							sleep(Convert.failTimeSpan * 1000);
						} 

					} catch (InterruptedException e) {
					}
				}
				try {

					if (Convert.urlfail) {
						sleep(Convert.failTimeSpan * 1000);
					} else {
						sleep(1000);
					}

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}
	};
	HttpGet getMet;
	HttpPost postMet;

	public void request(UrlSync urlSync) {
		getMet = null;
		postMet = null;
		if (urlSync.isGet()) {
			getMet = new HttpGet(urlSync.getAllUri());
		} else {
			postMet = new HttpPost(urlSync.getAllUri());
		}
		Log.e("request", urlSync.getAllUri());
		client = new DefaultHttpClient();
		client.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		try {
			if (urlSync.isGet()) {
				httpResponse = client.execute(getMet);

			} else {
				httpResponse = client.execute(postMet);
			}

			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 取出回应字串
				String strResult;

				strResult = EntityUtils.toString(httpResponse.getEntity());
					Log.e("request", "1");
					urlSync.setResult(strResult);
					if(urlSync.getResultType()==null){
						if(!"1".equals(strResult)){
						infoSync.savecontnet(strResult, auh,  urlSync);
						}
					}
					if("16".equals(urlSync.getResultType())||"10".equals(urlSync.getResultType())||"21".equals(urlSync.getResultType())){
						if("1".equals(strResult)){
							urlSync.setToast(false);
						}else{
							setWebUrl(strResult.split(";"));
						}
					}
					if("9".equals(urlSync.getResultType())){
						if("1".equals(strResult)){
							urlSync.setToast(false);
						}else{
							if(urlSync.getAllUri().contains("/delWeibo")){
								String[] bindArgs={Convert.uname,urlSync.getCode()};
								auh.getWritableDatabase().execSQL("delete from content where username=? and code=? ", bindArgs);
							}else{
								setWebUrl(strResult.split(";"));
							}
							
						}
					}
					
					
					Message msg=mMainHandler.obtainMessage();
					msg.obj=urlSync;
					msg.arg1=1;
					mMainHandler.sendMessage(msg);

			}else{
				Log.e("requestErr", "1");
			}
			Convert.urlfail=false;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			Convert.syncList.add(urlSync);
			Message msg=mMainHandler.obtainMessage();
			msg.obj=urlSync;
			msg.arg1=2;
			mMainHandler.sendMessage(msg);
			
			
			Convert.urlfail=true;
			Log.e("requestErr", "2");
			

		} finally {

		}

	}
	
	private void setWebUrl(String[] weburl){
		UrlSync urlSync;
		for (String weburi : weburl) {
			if("".equals(weburi)){
				continue;
			}
			urlSync=new UrlSync();
			urlSync.setNotice(false);
			urlSync.setUri(weburi);
			urlSync.setMaincode("main");
			urlSync.setSyncType(UrlSync.INFOALL);
			Convert.syncList.add(urlSync);
		}
	}
	


	public void imgsync() {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			auh = DBhelper.getDBHelper(context);
			Log.e("ImgNum", String.valueOf(num));
			if (num % 10 == 4) {
				imgSync.sync(null, auh, 1);
			} else {
				if (num % 10 == 7) {
					imgSync.sync(null, auh, 2);
				} else {
					imgSync.sync(null, auh, 0);
				}
			}
			num++;
		}
	}

	
	public void putNotic( String title, String content, String code) {
		// int s=new Date().getSeconds();
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification n = new Notification(R.drawable.moguico, content,
				System.currentTimeMillis());
		n.flags = Notification.FLAG_AUTO_CANCEL;
		// Intent i = new Intent(arg0.getContext(), NotificationShow.class);
		// i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
		// PendingIntent
		PendingIntent contentIntent = PendingIntent.getActivity(this,
				R.string.app_name, getI(code),
				PendingIntent.FLAG_UPDATE_CURRENT);

		n.setLatestEventInfo(this, title, content, contentIntent);

		nm.notify(numt++, n);
	}

	public Intent getI(String code) {
		int count = 0;
		try {
			synchronized (InfoSync.class) {
				readdb = auh.getReadableDatabase();
				Cursor activelist = readdb.rawQuery(
						"select * from activeuser ", null);
				count = activelist.getCount();
				activelist.close();
			}
		} catch (Exception t) {
			Log.e("E", t.getMessage() == null ? "" : t.getMessage());

		}

		// readdb.close();
		// auh.close();
		if (count == 0) {
			i = new Intent(InfoService.this, TMain.class);
		} else {
			i = new Intent(InfoService.this, Welcome.class);
			Uri uri = Uri.parse("?code:" + code);
			i.setData(uri);

		}

		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

		return i;
	}

}
